{% extends "teacher/base.html" %}

{% block title %}课程信息管理 - 期末成绩登记统计分析系统{% endblock %}

{% block styles %}
<style>
  .main-content {
    max-width: 1200px;
    margin: 0 auto;
    padding: 20px;
    margin-left: 250px;
    /* 为侧边栏留出空间 */
    margin-top: 60px;
    /* 为顶部导航栏留出空间 */
    min-height: calc(100vh - 60px);
    /* 减去导航栏高度 */
  }

  .action-bar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 25px;
    background: white;
    padding: 15px 20px;
    border-radius: var(--border-radius);
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
    position: sticky;
    top: 60px;
    /* 导航栏高度 */
    z-index: 100;
  }

  .search-box {
    display: flex;
    gap: 12px;
    flex: 1;
    max-width: 400px;
  }

  .search-box input {
    flex: 1;
    padding: 10px 15px;
    border: 1px solid #e0e0e0;
    border-radius: var(--border-radius);
    font-size: 14px;
    transition: all 0.3s ease;
  }

  .search-box input:focus {
    border-color: var(--primary-blue);
    box-shadow: 0 0 0 2px rgba(9, 132, 227, 0.1);
    outline: none;
  }

  .btn {
    padding: 10px 20px;
    border: none;
    border-radius: var(--border-radius);
    cursor: pointer;
    font-size: 14px;
    font-weight: 500;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    gap: 8px;
    transition: all 0.3s ease;
  }

  .btn i {
    font-size: 16px;
  }

  .btn-primary {
    background: var(--primary-blue);
    color: white;
  }

  .btn-primary:hover {
    background: #0873c4;
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(9, 132, 227, 0.2);
  }

  .btn-danger {
    background: #ff6b6b;
    color: white;
  }

  .btn-danger:hover {
    background: #ff5252;
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(255, 107, 107, 0.2);
  }

  .btn-success {
    background: #00b894;
    color: white;
  }

  .btn-success:hover {
    background: #00a884;
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(0, 184, 148, 0.2);
  }

  .table-container {
    background: white;
    border-radius: var(--border-radius);
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
    overflow: hidden;
    transition: all 0.3s ease;
  }

  .table-container:hover {
    box-shadow: 0 5px 15px rgba(0, 0, 0, 0.15);
  }

  .table {
    width: 100%;
    border-collapse: separate;
    border-spacing: 0;
  }

  .table th,
  .table td {
    padding: 15px 20px;
    text-align: left;
    border-bottom: 1px solid #eee;
  }

  .table th {
    background: #f8f9fa;
    font-weight: 600;
    color: var(--text-primary);
    font-size: 14px;
    text-transform: uppercase;
    letter-spacing: 0.5px;
  }

  .table td {
    color: var(--text-secondary);
    font-size: 14px;
  }

  .table tr:last-child td {
    border-bottom: none;
  }

  .table tr:hover td {
    background: #f8f9fa;
  }

  .table td .btn {
    padding: 6px 12px;
    font-size: 13px;
  }

  .modal {
    display: none;
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, 0.5);
    z-index: 1000;
    backdrop-filter: blur(4px);
  }

  .modal-content {
    position: relative;
    background: white;
    margin: 5% auto;
    width: 450px;
    border-radius: var(--border-radius);
    box-shadow: 0 5px 20px rgba(0, 0, 0, 0.15);
    animation: modalSlideIn 0.3s ease;
  }

  @keyframes modalSlideIn {
    from {
      transform: translateY(-20px);
      opacity: 0;
    }

    to {
      transform: translateY(0);
      opacity: 1;
    }
  }

  .modal-header {
    padding: 20px;
    border-bottom: 1px solid #eee;
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .modal-title {
    font-size: 20px;
    color: var(--text-primary);
    margin: 0;
    font-weight: 600;
  }

  .close {
    font-size: 24px;
    color: #666;
    cursor: pointer;
    transition: all 0.2s ease;
    width: 32px;
    height: 32px;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 50%;
  }

  .close:hover {
    background: #f8f9fa;
    color: var(--text-primary);
  }

  .form-group {
    margin-bottom: 20px;
    padding: 0 20px;
  }

  .form-group label {
    display: block;
    margin-bottom: 8px;
    color: var(--text-secondary);
    font-weight: 500;
    font-size: 14px;
  }

  .form-group input,
  .form-group select {
    width: 100%;
    padding: 10px 15px;
    border: 1px solid #e0e0e0;
    border-radius: var(--border-radius);
    font-size: 14px;
    transition: all 0.3s ease;
  }

  .form-group input:focus,
  .form-group select:focus {
    border-color: var(--primary-blue);
    box-shadow: 0 0 0 2px rgba(9, 132, 227, 0.1);
    outline: none;
  }

  .modal-footer {
    padding: 20px;
    border-top: 1px solid #eee;
    display: flex;
    justify-content: flex-end;
    gap: 12px;
  }

  .pagination {
    display: flex;
    justify-content: center;
    align-items: center;
    gap: 15px;
    margin-top: 25px;
    padding: 15px;
    background: white;
    border-radius: var(--border-radius);
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  }

  .pagination .btn {
    padding: 8px 16px;
    min-width: 100px;
    background: white;
    color: var(--primary-blue);
    border: 1px solid var(--primary-blue);
    transition: all 0.3s ease;
  }

  .pagination .btn:hover:not(:disabled) {
    background: var(--primary-blue);
    color: white;
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(9, 132, 227, 0.2);
  }

  .pagination .btn:disabled {
    background: #f8f9fa;
    color: #6c757d;
    border-color: #dee2e6;
    cursor: not-allowed;
    transform: none;
    box-shadow: none;
  }

  .current-page {
    color: var(--text-primary);
    font-weight: 500;
    font-size: 14px;
    padding: 0 15px;
  }

  /* 响应式布局调整 */
  @media (max-width: 768px) {
    .main-content {
      margin-left: 0;
      padding: 15px;
    }

    .action-bar {
      position: relative;
      top: 0;
    }

    .search-box {
      max-width: 100%;
    }

    .table-container {
      overflow-x: auto;
    }

    .modal-content {
      width: 90%;
      margin: 10% auto;
    }

    .pagination {
      flex-direction: column;
      gap: 10px;
      padding: 10px;
    }

    .pagination .btn {
      width: 100%;
    }

    .current-page {
      order: -1;
      margin-bottom: 5px;
    }
  }
</style>
{% endblock %}

{% block content %}
<div class="action-bar">
  <div class="search-box">
    <input type="text" id="searchInput" placeholder="搜索课程...">
    <button class="btn btn-primary" onclick="searchCourses()">搜索</button>
  </div>
  <button class="btn btn-primary" onclick="showAddModal()">添加课程</button>
</div>

<div class="table-container">
  <table class="table">
    <thead>
      <tr>
        <th>课程编号</th>
        <th>课程名称</th>
        <th>所属学院</th>
        <th>学分</th>
        <th>学期</th>
        <th>操作</th>
      </tr>
    </thead>
    <tbody id="courseTableBody">
      {# 遍历分页对象时要加 .items #}
      {% for course, college_name in courses.items %}
      <tr>
        <td>{{ course.course_id }}</td>
        <td>{{ course.course_name }}</td>
        <td>{{ college_name }}</td>
        <td>{{ course.credits }}</td>
        <td>{{ course.semester }}</td>
        <td>
          <button class="btn btn-primary" onclick="showEditModal('{{ course.course_id }}')">编辑</button>
          <button class="btn btn-danger" onclick="deleteCourse('{{ course.course_id }}')">删除</button>
        </td>
      </tr>
      {% endfor %}
    </tbody>
  </table>

  <!-- 分页控件 -->
  {% if courses.total > 20 %}
  <div class="pagination">
    {% if courses.has_prev %}
    <a href="{{ url_for('teacher_course.courses', page=courses.prev_num) }}" class="btn btn-primary">上一页</a>
    {% else %}
    <button class="btn" disabled>上一页</button>
    {% endif %}

    <span class="current-page">第 {{ courses.page }} 页，共 {{ courses.pages }} 页</span>

    {% if courses.has_next %}
    <a href="{{ url_for('teacher_course.courses', page=courses.next_num) }}" class="btn btn-primary">下一页</a>
    {% else %}
    <button class="btn" disabled>下一页</button>
    {% endif %}
  </div>
  {% endif %}
</div>

<!-- 添加/编辑课程模态框 -->
<div id="courseModal" class="modal">
  <div class="modal-content">
    <div class="modal-header">
      <h3 class="modal-title" id="modalTitle">添加课程</h3>
      <span class="close" onclick="closeModal()">&times;</span>
    </div>
    <form id="courseForm">
      <input type="hidden" id="courseId">
      <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
      <div class="form-group">
        <label for="courseName">课程名称</label>
        <input type="text" id="courseName" required>
      </div>
      <div class="form-group">
        <label for="collegeId">所属学院</label>
        <select id="collegeId" required>
          {% for college in colleges %}
          <option value="{{ college.college_id }}">{{ college.college_name }}</option>
          {% endfor %}
        </select>
      </div>
      <div class="form-group">
        <label for="credits">学分</label>
        <input type="number" id="credits" min="0" max="10" step="0.5" required>
      </div>
      <div class="form-group">
        <label for="semester">学期</label>
        <select id="semester" required>
          {% for semester in semesters %}
          <option value="{{ semester }}">{{ semester }}</option>
          {% endfor %}
        </select>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-primary" onclick="closeModal()">取消</button>
        <button type="submit" class="btn btn-success">保存</button>
      </div>
    </form>
  </div>
</div>

<script>
  // 获取CSRF token
  function getCsrfToken() {
    return document.querySelector('input[name="csrf_token"]').value;
  }

  // 显示添加模态框
  function showAddModal() {
    document.getElementById('modalTitle').textContent = '添加课程';
    document.getElementById('courseForm').reset();
    document.getElementById('courseId').value = '';
    document.getElementById('courseModal').style.display = 'block';
  }

  // 显示编辑模态框
  function showEditModal(courseId) {
    document.getElementById('modalTitle').textContent = '编辑课程';
    // 获取课程信息并填充表单
    fetch(`/teacher/api/courses/${courseId}`)
      .then(response => {
        console.log('Response status:', response.status);
        return response.json().then(data => {
          if (!response.ok) {
            throw new Error(data.message || '获取课程信息失败');
          }
          return data;
        });
      })
      .then(data => {
        if (data.success && data.data) {
          const course = data.data;
          console.log('Course data:', course);
          document.getElementById('courseId').value = course.course_id;
          document.getElementById('courseName').value = course.course_name;
          document.getElementById('collegeId').value = course.college_id;
          document.getElementById('credits').value = course.credits;
          document.getElementById('semester').value = course.semester;
          document.getElementById('courseModal').style.display = 'block';
        } else {
          throw new Error(data.message || '获取课程信息失败');
        }
      })
      .catch(error => {
        console.error('Error:', error);
        alert(error.message || '获取课程信息失败，请重试');
      });
  }

  // 关闭模态框
  function closeModal() {
    document.getElementById('courseModal').style.display = 'none';
    document.getElementById('courseForm').reset();
  }

  // 删除课程
  function deleteCourse(courseId) {
    if (!confirm('确定要删除这个课程吗？')) return;
    fetch(`/teacher/api/courses/${courseId}`, {
      method: 'DELETE',
      headers: {
        'X-CSRFToken': getCsrfToken()
      }
    })
      .then(response => response.json().catch(() => {
        throw new Error('服务器返回了非JSON格式的错误信息');
      }))
      .then(data => {
        if (data.success) {
          alert('课程删除成功');
          window.location.reload();
        } else {
          alert(data.message || '删除失败');
        }
      })
      .catch(error => {
        alert(error.message || '删除失败，请重试');
      });
  }

  // 搜索课程
  function searchCourses() {
    const searchText = document.getElementById('searchInput').value.trim();
    const page = 1; // 重置到第一页

    // 显示加载状态
    const tbody = document.getElementById('courseTableBody');
    tbody.innerHTML = '<tr><td colspan="6" style="text-align: center;">正在搜索...</td></tr>';

    fetch(`/teacher/api/courses?search=${encodeURIComponent(searchText)}&page=${page}`, {
      headers: {
        'X-CSRFToken': getCsrfToken()
      }
    })
      .then(response => {
        if (!response.ok) {
          throw new Error(`搜索请求失败: ${response.status}`);
        }
        return response.json();
      })
      .then(data => {
        tbody.innerHTML = '';

        if (data.success && data.courses && data.courses.length > 0) {
          data.courses.forEach(course => {
            const row = document.createElement('tr');
            row.setAttribute('data-course-id', course.course_id);
            row.innerHTML = `
              <td>${course.course_id || ''}</td>
              <td>${course.course_name || ''}</td>
              <td>${course.college_name || ''}</td>
              <td>${course.credits || ''}</td>
              <td>${course.semester || ''}</td>
              <td>
                <button class="btn btn-primary" onclick="showEditModal('${course.course_id}')">编辑</button>
                <button class="btn btn-danger" onclick="deleteCourse('${course.course_id}')">删除</button>
              </td>
            `;
            tbody.appendChild(row);
          });
        } else {
          tbody.innerHTML = '<tr><td colspan="6" style="text-align: center;">没有找到匹配的课程</td></tr>';
        }

        // 更新分页控件
        if (data.pagination) {
          updatePagination(data.pagination);
        }
      })
      .catch(error => {
        console.error('Error:', error);
        tbody.innerHTML = `<tr><td colspan="6" style="text-align: center; color: red;">搜索失败: ${error.message}</td></tr>`;
      });
  }

  // 添加搜索框回车事件
  document.getElementById('searchInput').addEventListener('keypress', function (e) {
    if (e.key === 'Enter') {
      searchCourses();
    }
  });

  // 更新分页控件
  function updatePagination(pagination) {
    const paginationDiv = document.querySelector('.pagination');
    if (!paginationDiv) return;

    // 只有当总记录数大于20时才显示分页
    if (pagination.total <= 20) {
      paginationDiv.style.display = 'none';
      return;
    }

    paginationDiv.style.display = 'flex';
    paginationDiv.innerHTML = '';

    const prevButton = document.createElement(pagination.has_prev ? 'a' : 'button');
    prevButton.className = 'btn btn-primary';
    prevButton.textContent = '上一页';
    if (pagination.has_prev) {
      prevButton.href = `?page=${pagination.current_page - 1}`;
    } else {
      prevButton.disabled = true;
    }
    paginationDiv.appendChild(prevButton);

    const pageInfo = document.createElement('span');
    pageInfo.className = 'current-page';
    pageInfo.textContent = `第 ${pagination.current_page} 页，共 ${pagination.pages} 页`;
    paginationDiv.appendChild(pageInfo);

    const nextButton = document.createElement(pagination.has_next ? 'a' : 'button');
    nextButton.className = 'btn btn-primary';
    nextButton.textContent = '下一页';
    if (pagination.has_next) {
      nextButton.href = `?page=${pagination.current_page + 1}`;
    } else {
      nextButton.disabled = true;
    }
    paginationDiv.appendChild(nextButton);
  }

  // 提交表单
  document.getElementById('courseForm').onsubmit = function (e) {
    e.preventDefault();
    const courseId = document.getElementById('courseId').value;
    const courseName = document.getElementById('courseName').value;
    const collegeId = document.getElementById('collegeId').value;
    const credits = document.getElementById('credits').value;
    const semester = document.getElementById('semester').value;

    // 验证输入
    if (!courseName || !collegeId || !credits || !semester) {
      alert('请填写所有必填字段');
      return;
    }

    const data = {
      course_name: courseName,
      college_id: parseInt(collegeId),
      credits: parseFloat(credits),
      semester: semester
    };

    const url = courseId ? `/teacher/api/courses/${courseId}` : '/teacher/api/courses';
    const method = courseId ? 'PUT' : 'POST';

    // 禁用提交按钮，防止重复提交
    const submitButton = this.querySelector('button[type="submit"]');
    submitButton.disabled = true;
    submitButton.textContent = '保存中...';

    fetch(url, {
      method: method,
      headers: {
        'Content-Type': 'application/json',
        'X-CSRFToken': getCsrfToken()
      },
      body: JSON.stringify(data)
    })
      .then(response => response.json())
      .then(data => {
        if (data.success) {
          alert('保存成功');
          // 关闭模态框
          closeModal();
          // 重新加载页面
          window.location.reload();
        } else {
          throw new Error(data.message || '保存失败');
        }
      })
      .catch(error => {
        console.error('Error:', error);
        alert(error.message || '保存失败，请稍后重试');
        // 恢复提交按钮状态
        submitButton.disabled = false;
        submitButton.textContent = '保存';
      });
  };
</script>
{% endblock %}